package com.core.image.handler;

import com.core.image.tcp.ConnectorHandler;

/**
 * describe:
 *
 * @author 库琦
 * @date 2020/02/04/20:43
 */
public abstract class ConnectorHandlerChain<Model> {
    //当前一个新的节点到当前链式结构的末尾
    private volatile ConnectorHandlerChain<Model> next;

    /**
     * 添加一个新的节点到当前链式结构的末尾
     * @param newChain
     * @return
     */
    public ConnectorHandlerChain<Model> appendLast(ConnectorHandlerChain<Model> newChain){
        if (newChain == this || this.getClass().equals(newChain.getClass())){
            return this;
        }
        synchronized (this){
            if (next == null){
                next = newChain;
                return newChain;
            }
            return next.appendLast(newChain);
        }
    }

    /**
     * 删除某个节点
     * @param clx
     * @return
     */
    public synchronized boolean remove(Class <? extends ConnectorHandlerChain<Model>> clx){
        if (this.getClass().equals(clx)){
            return false;
        }
        synchronized (this){
            if (next == null){
                return false;
            }else if (next.getClass().equals(clx)){
                next =next.next;
                return true;
            }else {
                return next.remove(clx);
            }
        }
    }

    /**
     * 优先自己消费，如果自己未消费，则给next消费。
     * @param clientHandler
     * @param model
     * @return
     */
  public   synchronized   boolean  handler(ConnectorHandler clientHandler, Model model){
        ConnectorHandlerChain<Model> next = this.next;
        if (consume(clientHandler,model)){
            return true;
        }
        boolean consumed = next != null && next.handler(clientHandler,model);
        if (consumed){
            return true;
        }
        return consumeAgain(clientHandler,model);
      }

    public    boolean consumeAgain(ConnectorHandler clientHandler, Model model) {
        return false;
    }
    public   abstract   boolean consume(ConnectorHandler clientHandler, Model model);


}
